/*
 * Copyright 2013-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tinem.platform.web.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.pojo.co.JwtPropertyName;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;

/**
 * @author Spencer Gibb
 */
@Component
public class JitSessionGatewayFilterFactory
		extends AbstractGatewayFilterFactory<Object> {
	@Override
	public GatewayFilter apply(Object config) {
		return (exchange, chain) -> exchange.getPrincipal()
				.cast(JwtAuthenticationToken.class)
				.flatMap(jwtAuthenticationToken -> {
					String jti = jwtAuthenticationToken.getToken().getClaimAsString(JwtPropertyName.JTI);
					exchange.getAttributes().put(GatewayHeadName.X_PLATFORM_GATEWAY_CONTEXT_JTI,jti);
					ServerHttpRequest request = exchange.getRequest().mutate()
							.headers(httpHeaders -> httpHeaders.put(GatewayHeadName.X_PLATFORM_GATEWAY_CONTEXT_JTI, CollUtil.newArrayList(jti)))
							.build();
					return chain.filter(exchange.mutate().request(request).build());
				});
	}

}
